import {HttpProxyAgent} from "http-proxy-agent";
import {HttpsProxyAgent} from "https-proxy-agent";
import axios from "axios";
import {initVmSync} from "./utils.js";
import fs from "fs";

let print = console.log
let config = {
    domUrl: 'https://www.google.com/travel/flights/booking?tfs=CBwQAhpJEgoyMDI0LTExLTA2Ih8KA0hLRxIKMjAyNC0xMS0wNhoDTlJUKgJIQjIDMzIwagwIAhIIL20vMDNoNjRyDAgCEggvbS8wN2RmaxpJEgoyMDI0LTExLTIwIh8KA05SVBIKMjAyNC0xMS0yMBoDSEtHKgJIQjIDMzIzagwIAhIIL20vMDdkZmtyDAgCEggvbS8wM2g2NEABSAFwAYIBCwj___________8BmAEB&tfu=CmxDalJJZDFWaVpURnpjbFZxUkc5QlRteFpNMmRDUnkwdExTMHRMUzB0TFhSaVluZHdORUZCUVVGQlIyTlhUMDF6UVdGMk5tZEJFZ1ZJUWpNeU14b0tDSUlQRUFBYUEwaExSRGdjY0piQkFRPT0SBggAIAEoCCIA&hl=en&gl=HK',
    script_name: 'https://www.gstatic.com/',
    debug: false,
    proxy: false,
    keepRandom: false,
    body: '',
    cookie: undefined,
    cookie2: undefined,

    type: 'ksada'


}

function randomSessionId() {
    let strs = 'abcdefghijklmnopqrstuvwxyz1234567890';
    let sessionID = '';
    for (let i = 0; i < 8; i++) {
        sessionID += strs.charAt(parseInt(Math.random() * strs.length))
    }
    return sessionID;
}

let uri = 'https://www.google.com/travel/flights/booking?tfs=CBwQAhpKEgoyMDI1LTAyLTEwIiAKA0JPUxIKMjAyNS0wMi0xMBoDTUNPKgJGOTIEMTk3N2oMCAMSCC9tLzAxY3hfcgwIAxIIL20vMHBseTAaShIKMjAyNS0wMi0xMiIgCgNNQ08SCjIwMjUtMDItMTIaA0JPUyoCRjkyBDMzNDhqDAgDEggvbS8wcGx5MHIMCAMSCC9tLzAxY3hfQAFIAXABggELCP___________wGYAQE&tfu=CmxDalJJVFZSQ2JXRnpOSGhGZFhkQlFrdDJPR2RDUnkwdExTMHRMUzB0ZEdKaVozWXpOa0ZCUVVGQlIyVnJXbVk0UlU0dGRqSkJFZ1pHT1RNek5EZ2FDZ2lyTkJBQ0dnTlZVMFE0SEhDck5BPT0SAggAIgMKATA&gl=US';

let proxy = {
    // "password": "WPxpuBFj", "server": "10.188.200.27:31502",
    "password": "WPxpuBFj", "server": "127.0.0.1:7890",
    "username": "userID-734-orderid-9670-region-us-sessionID-123123-sessiontime-5"
}
let users = proxy.username.split('-')
let sessIdIdx = users.indexOf('sessionID') + 1;
users[sessIdIdx] = randomSessionId();
proxy.username = users.join('-')
const httpAgent = new HttpProxyAgent(`http://${users.join('-')}:${proxy.password}@${proxy.server}`, {
    timeout: 9000,
});
const httpsAgent = new HttpsProxyAgent(`http://${users.join('-')}:${proxy.password}@${proxy.server}`, {
    timeout: 9000,
});
proxy = {
    host: proxy.server.split(':')[0],
    port: parseInt(proxy.server.split(':')[1]), // 如果你的代理服务器需要认证，则还需要添加：
    auth: {
        username: users.join('-'),
        password: proxy.password
    },
    protocol: 'http'
}
let client = axios.create({
    timeout: 9000,
    maxBodyLength: 1024 * 1024 * 1024 * 1024,
    httpAgent: httpAgent,
    httpsAgent: httpsAgent
    // proxy: proxy
});


async function getData() {
    let r = await client.request({
        url: uri,
        headers: {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "en",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=0, i",
            "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
            "sec-ch-ua-arch": "\"arm\"",
            "sec-ch-ua-bitness": "\"64\"",
            "sec-ch-ua-form-factors": "\"Desktop\"",
            "sec-ch-ua-full-version": "\"131.0.6778.70\"",
            "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.70\", \"Chromium\";v=\"131.0.6778.70\", \"Not_A Brand\";v=\"24.0.0.0\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-model": "\"\"",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-ch-ua-platform-version": "\"15.1.0\"",
            "sec-ch-ua-wow64": "?0",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "x-browser-channel": "stable",
            "Referer": "https://www.google.com/travel/flights/search?tfs=CBwQAhooEgoyMDI1LTAyLTEwagwIAxIIL20vMDFjeF9yDAgDEggvbS8wcGx5MBooEgoyMDI1LTAyLTEyagwIAxIIL20vMHBseTByDAgDEggvbS8wMWN4X0ABSAFwAYIBCwj___________8BmAEB&tfu=EgQIABAAIgA&gl=TW",
            "Referrer-Policy": "strict-origin-when-cross-origin"
        }
    })



    // 假设 text 是输入的字符串
    const text = r.data

// 正则匹配提取 mnsUbf 的值
    const mnsUbf = text.match(/mnsUbf":"(.+?)","nQyAE/)[1];

// 处理字符串
    let data = '[' + mnsUbf.slice(4);

// 处理 unicode-escape 解码
    data = Buffer.from(data).toString('utf-8'); // 自动处理 unicode 转义
    let d1 = data.replace(/\\?\\u(\w{4})/g, (a, b) => String.fromCharCode(parseInt(b, 16)));

// 如果遇到需要特殊处理的 unicode 字符（如 \uXXXX 格式）
// 可以用以下方式强制解码：
    data = JSON.parse(d1.replaceAll('\\"','"').replaceAll('\\\\"','\\"'))


    let long_str = data[0]
    let func = data[5][5]
    return {
        'func': func.split('\\n').slice(1,).join('\\n')
            .replaceAll(',\\n',',')
            // .replaceAll('\\\\n','\\n')
            .replaceAll('\\\\','\\'),
        'long_str': long_str
    }
}

getData().then(e=>{

    let userCode = `
    var _replace = String.prototype.replace;
var _match = String.prototype.match;
String.prototype.replace = function (oldStr, newStr) {
    // console.log('_replace',oldStr,  this)
    if (newStr === '\\n') {
        console.log('_replace', oldStr, this.toString())
        // if (this.toString().length === 7){
        // debugger;
        // }

        // debugger;
    }
    let res = _replace.apply(this, arguments)
    return res;

}
// String.prototype.match = function (mm){
//     let res = _match.apply(this, arguments)
//     print('_match', this.toString(), mm, '=', res);
//     return res;
// }
var _concat = Array.prototype.concat;
Array.prototype.concat = function () {
    let res = _concat.apply(this, arguments)
    print('_concat', this + '', arguments[0] + '')
    return res;

};
    
    ` + e.func
        + `;;
    
    let b = "${e.long_str}";;
    
    const c = new window.ridgeslice.gc(b);
window.sign = c;`

    fs.writeFileSync('./glf1.js', userCode)
    fs.writeFileSync('./glf2.js', e.func)
    // let userCode = fs.readFileSync('tests/dy.js', 'utf8').toString();
// let userCode = fs.readFileSync('/Users/wang/Documents/jsvmp/learn/ksada/out2.js', 'utf8').toString();
    let html = fs.readFileSync('demo.html', 'utf8').toString();

    let {vm, context} = initVmSync(userCode, config, html)

    let a = "[null,\"[[null,\\\"CjRIS2tscFpWR1ZmNVlBQlNXQ0FCRy0tLS0tLS0tLS10YmwzNUFBQUFBR2N5NDNjS281TmFBEgVXUzQ1NBoKCIcfEAAaA0hLRDgccKaPAw==\\\"],[null,null,1,null,[],1,[1,0,0,0],null,null,null,null,null,null,[[[[[\\\"YXE\\\",0]]],[[[\\\"YYC\\\",0]]],null,0,null,null,\\\"2024-11-19\\\",null,[[\\\"YXE\\\",\\\"2024-11-19\\\",\\\"YYC\\\",null,\\\"WS\\\",\\\"359\\\"]],null,null,null,null,null,3],[[[[\\\"YYC\\\",0]]],[[[\\\"YXE\\\",0]]],null,0,null,null,\\\"2024-12-02\\\",null,[[\\\"YYC\\\",\\\"2024-12-02\\\",\\\"YXE\\\",null,\\\"WS\\\",\\\"454\\\"]],null,null,null,null,null,3]],null,null,null,1],null,0]\"]";
    // a = req.body
    new Promise((e, r) => {
        // console.log()
        context.sign.ply(e, !0, Object.fromEntries([['mgGpzd', a]]))
    }).then(e => {
        debugger;
        // console.log(e)
        print(e.length)
    }).catch(e => {
        debugger;
        print(e)
    })
})
